//# COMP 355    #  WONG YI CHUN        07017375         eg_wycaa
package com.jimmyapp.papa;

import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;

import com.jimmyapp.papa.game.GameGenerator;
import com.jimmyapp.papa.game.GameInterface;
import com.jimmyapp.papa.game.GameListener;
import com.jimmyapp.papa.game.GameState;
import com.jimmyapp.papa.game.SessionEvents.AuthListener;
import com.jimmyapp.papa.game.SessionEvents.LogoutListener;

import com.jimmyapp.papa.game.ui.BoxGame3DView;
import com.jimmyapp.papa.game.ui.IntroductionView;
import com.jimmyapp.papa.game.ui.LoginButton;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Configuration;
import android.graphics.Color;

import android.media.AudioManager;

import android.media.SoundPool;
import android.opengl.GLSurfaceView;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Vibrator;

import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;

import android.view.WindowManager;
import android.view.View.OnTouchListener;

import android.widget.ImageView;

import android.widget.Button;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import android.util.Log;

public class GameActivity extends Activity implements DialogListener,GameListener{

	private BoxGame3DView gameView;
	private static Vibrator vibrator;
	public static final String APP_ID = "220295697999410";
	private int volume;
	private int soundEffect;
	private Facebook mFacebook;
	private AsyncFacebookRunner mAsyncRunner;
	private TextView leftTxt;
	private TextView timeTxt;
	private LoginButton fbLogin;
	private Bundle parameters;
	private Button againBut;
	private boolean vibrate;
	private boolean sound;
	private SoundPool sp;
	private int sumScore = 0;
	private int screenHeight;
	private int screenWidth;
	private View vl;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE))
				.getDefaultDisplay();

		screenHeight = display.getHeight();
		screenWidth = display.getWidth();
		IntroductionView introView = GameGenerator.IntroViewFactory(
				this.getApplicationContext(), screenHeight, screenWidth);
		vibrate = this.getIntent().getExtras()
				.getBoolean("vibrate", false);
		sound = this.getIntent().getExtras()
				.getBoolean("sound", false);
		if (vibrator == null && vibrate) {
			vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
		}
		gameView = new BoxGame3DView(this,
					screenHeight, screenWidth);
		gameView.setGameCode(introView.gameCode);
		parameters = new Bundle();
		mFacebook = new Facebook(APP_ID);
		mAsyncRunner = new AsyncFacebookRunner(mFacebook);
		LayoutInflater li = this.getLayoutInflater();
		vl = li.inflate(R.layout.game, null);
		fbLogin = (LoginButton)vl.findViewById(R.id.tableRow3)
		.findViewById(R.id.linearLayout2).findViewById(R.id.login);
		againBut = (Button)vl.findViewById(R.id.tableRow3)
		.findViewById(R.id.linearLayout2).findViewById(R.id.againBut);
		againBut.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View arg0) {
				restart();
			}
		});
		fbLogin.init(this, mFacebook);
		com.jimmyapp.papa.game.SessionStore.restore(mFacebook, this);
		com.jimmyapp.papa.game.SessionEvents
				.addAuthListener(new AuthListener() {

					@Override
					public void onAuthSucceed() {
						
						mFacebook.dialog(GameActivity.this, "stream.publish",parameters,GameActivity.this);
					}

					@Override
					public void onAuthFail(String error) {
						
					}

				});
		com.jimmyapp.papa.game.SessionEvents
				.addLogoutListener(new LogoutListener() {

					@Override
					public void onLogoutBegin() {
						
					}

					@Override
					public void onLogoutFinish() {

					}

				});
		
		

		final TableRow row = (TableRow) vl.findViewById(R.id.tableRow1);
		
		sp = (sound) ? new SoundPool(1,
				AudioManager.STREAM_MUSIC, 0) : null;

		
		if (sound) {
			final AudioManager am = (AudioManager) this
					.getSystemService(Context.AUDIO_SERVICE);
			volume = am.getStreamVolume(AudioManager.STREAM_MUSIC);
			soundEffect = sp.load(this.getApplicationContext(),
					R.raw.failbuzzer, 1);
		}
		ImageView rb = (ImageView) vl.findViewById(R.id.redBut);
		rb.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (v instanceof ImageView) {
					if (clickButton((ImageView) v, event.getAction(),
							R.drawable.redbut, R.drawable.redbutp)) {
						GameInterface gi = (GameInterface) gameView;
						if (gi.getGameState().equals(GameState.INGAME)) {
							if (!gi.clickView(Color.RED)) {
								if (sound) {
									sp.play(soundEffect, volume, volume, 1, 0,
											1f);
								}
								if (vibrate) {
									vibrator.vibrate(500);
								} 
							}else {
								if (vibrate) {
									vibrator.vibrate(50);
								}
							}
						}
					}
				}
				return false;
			}
		});
		ImageView gb = (ImageView) vl.findViewById(R.id.greenBut);
		gb.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (v instanceof ImageView) {
					if (clickButton((ImageView) v, event.getAction(),
							R.drawable.greenbut, R.drawable.greenbutp)) {
						GameInterface gi = (GameInterface) gameView;
						if (gi.getGameState().equals(GameState.INGAME)) {
							if (!gi.clickView(Color.GREEN)) {
								if (sound) {
									sp.play(soundEffect, volume, volume, 1, 0,
											1f);
								}
								if (vibrate) {
									vibrator.vibrate(500);
								}
							} else {
								if (vibrate) {
									vibrator.vibrate(50);
								}
							}
						}
					}
				}
				return false;
			}
		});
		ImageView bb = (ImageView) vl.findViewById(R.id.blueBut);
		bb.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (v instanceof ImageView) {
					if (clickButton((ImageView) v, event.getAction(),
							R.drawable.bluebut, R.drawable.bluebutp)) {
						GameInterface gi = (GameInterface) gameView;
						if (gi.getGameState().equals(GameState.INGAME)) {
							if (!gi.clickView(Color.BLUE)) {
								if (sound) {
									sp.play(soundEffect, volume, volume, 1, 0,
											1f);
								}
								if (vibrate) {
									vibrator.vibrate(500);
								}
							} else if (vibrate) {
								vibrator.vibrate(50);
							} 
						}
					}
				}
				return false;
			}
		});
		row.setGravity(Gravity.CENTER);
		introView.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent arg1) {
				IntroductionView view = (IntroductionView) v;
				if (view.state.equals(GameState.READY)
						&& arg1.getAction() == MotionEvent.ACTION_DOWN) {
					view.postInvalidate();
					GameActivity.this.setContentView(vl);
					GLSurfaceView view3d = (GLSurfaceView) gameView;
					TableRow.LayoutParams lp = new TableRow.LayoutParams();
					lp.height = screenHeight - 170;
					lp.width = screenWidth;
					row.addView(view3d, lp);
					view3d.requestRender();
					v.setClickable(false);
					v.setEnabled(false);
					gameView.startGame();
					cdt.start();
					
					return true;
				}
				return false;
			}
		});

		timeTxt = (TextView) vl.findViewById(R.id.tableRow3)
			.findViewById(R.id.linearLayout2).findViewById(R.id.timeText);
		timeTxt.setTextSize(9);
		leftTxt = (TextView) vl.findViewById(R.id.tableRow3)
		.findViewById(R.id.linearLayout2).findViewById(R.id.textView1);
		leftTxt.setTextSize(10);
		fbLogin.setVisibility(View.GONE);
		setTimer();
		Thread thread = new Thread(introView);
		thread.start();
		
		this.setContentView(introView);
	}
	private void restart() {
		leftTxt.setVisibility(View.VISIBLE);
		fbLogin.setVisibility(View.GONE);
		againBut.setVisibility(View.GONE);
		IntroductionView introView = GameGenerator.IntroViewFactory(
				this.getApplicationContext(), screenHeight, screenWidth);
		this.setContentView(introView);
		gameView = new BoxGame3DView(this,
				screenHeight, screenWidth);
		gameView.setGameCode(introView.gameCode);
		
		Thread thread = new Thread(introView);
		thread.start();
		
		final TableRow row = (TableRow) vl.findViewById(R.id.tableRow1);
		row.removeAllViews();
		introView.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent arg1) {
				IntroductionView view = (IntroductionView) v;
				if (view.state.equals(GameState.READY)
						&& arg1.getAction() == MotionEvent.ACTION_DOWN) {
					view.postInvalidate();
					GameActivity.this.setContentView(vl);
					GLSurfaceView view3d = (GLSurfaceView) gameView;
					GameInterface gi = (GameInterface) gameView;
					TableRow.LayoutParams lp = new TableRow.LayoutParams();
					lp.height = screenHeight - 170;
					lp.width = screenWidth;
					row.addView(view3d, lp);
					view3d.requestRender();
					v.setClickable(false);
					v.setEnabled(false);
					cdt.start();
					gameView.startGame();
					return true;
				}
				return false;
			}
		});
		
		
	}
	private void setTimer() {
		cdt = new CountDownTimer(30000, 100) {
			public void onTick(long millisUntilFinished) {
				timeTxt.setText(millisUntilFinished / 1000 + "."
						+ millisUntilFinished % 1000 + " sec");
				GameInterface gi = (GameInterface) gameView;
				if (gi.getGameState().equals(GameState.WRONG)) {
					if (penalty == 0) {
						penalty = millisUntilFinished - (2000 - offset);
						offset = 0;

					} else if (penalty > millisUntilFinished) {
						offset = penalty - millisUntilFinished;
						penalty = 0;
						gi.resumeFromPenalty();
					}
				}
			}
			
			public void onFinish() {
				offset = 0;
				GameInterface gi = (GameInterface) gameView;
				int score = gi.getScore();
				gi.gameOver();
				sumScore += score;
				leftTxt.setVisibility(View.GONE);
				againBut.setVisibility(View.VISIBLE);
				Log.i("sumScore", sumScore+"");
				if (score < 30) {
					againBut.setText(R.string.again);
					parameters.putString("attachment", "{\"name\":\"Papa game\",\"caption\":\"{*actor*} got "+sumScore+" score in Papa game!\"}");
					timeTxt.setText("Total socre:" + sumScore+". Post on facebook?");
					fbLogin.setVisibility(View.VISIBLE);
					sumScore = 0;
				} else {
					againBut.setText(R.string.next);
					timeTxt.setText("You scores " + score);
					cdt.cancel();
				}
			}
		};
	}
	private long penalty = 0;
	private long offset = 0;
	private CountDownTimer cdt;

	private boolean clickButton(ImageView v, int event, int srcID, int tarID) {
		switch (event) {
		case MotionEvent.ACTION_DOWN:
			v.setImageResource(tarID);
			return true;
		default:
			v.setImageResource(srcID);
		}
		return false;

	}

	@Override
	public void onConfigurationChanged(Configuration config) {
		super.onConfigurationChanged(config);
	}

	@Override
	public void onBackPressed() {

		Builder builder = new AlertDialog.Builder(this);
		builder.setMessage("Are you sure you want to exit?")
				.setCancelable(false)
				.setPositiveButton("Yes",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								dialog.dismiss();
								GameActivity.this.gameView.stop();
								
								GameActivity.this.finish();
							}
						})
				.setNegativeButton("No", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						dialog.dismiss();
					}
				});

		builder.create().show();

	}

	@Override
	protected void onDestroy() {
		if (gameView != null) {
			gameView.stop();
		}
		super.onDestroy();

	}

	@Override
	protected void onPause() {
		Log.i("on pause", "in pause");
		super.onPause();
	}

	protected void onResume() {

		super.onResume();
	}
	@Override
	public void onComplete(Bundle values) {
		Toast.makeText(this,"Action complete", Toast.LENGTH_SHORT);
	}
	@Override
	public void onFacebookError(FacebookError e) {
		Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG);
	}
	@Override
	public void onError(DialogError e) {
		Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG);
	}
	@Override
	public void onCancel() {
		
	}
	@Override
	public void fail() {
		if (sound) {
			sp.play(soundEffect, volume, volume, 1, 0,
					1f);
		}
		if (vibrate) {
			vibrator.vibrate(500);
		}
	}
}
